package com.it.emall.controller;

import com.it.emall.service.UserFavoritesService;
import com.it.emall.utils.JwtHelper;
import com.it.emall.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 收藏controller
 */
@RestController
@RequestMapping("/wx/favorites")
public class UserFavoritesController {
    @Autowired
    private UserFavoritesService userFavoritesService;
    JwtHelper jwtHelper=new JwtHelper();
    /**
     * 收藏/取消收藏食谱
     * @param token 解密获取用户ID
     * @param recipeId 食谱ID
     * @return 响应数据
     */
    @PostMapping("/toggle")
    public Object toggleFavorite(@RequestParam Integer recipeId,@RequestHeader("token") String token) {
        //解密token
        Integer userId=jwtHelper.verifyTokenAndGetUserId(token);

        int result = userFavoritesService.toggleFavorite(userId, recipeId);
        if (result == 0) {
            return ResponseUtils.ok("收藏成功");
        } else if (result == 1) {
            return ResponseUtils.ok("取消收藏成功");
        } else {
            return ResponseUtils.fail(500, "收藏操作失败");
        }
    }

    /**
     * 查看用户的收藏夹
     * @param token 用户ID
     * @return 响应数据
     */
    @GetMapping("/list")
    public Object getUserFavorites(@RequestHeader("token") String token) {
        //解密token
        Integer userId=jwtHelper.verifyTokenAndGetUserId(token);
        return ResponseUtils.ok(userFavoritesService.getUserFavorites(userId));
    }


    /**
     * 删除收藏食谱
     * @param token 用户ID
     * @param recipeId 食谱ID
     * @return 响应数据
     */
    @DeleteMapping("/delete")
    public Object deleteFavorite(@RequestHeader("token") String token, @RequestParam Integer recipeId) {
        Integer userId=jwtHelper.verifyTokenAndGetUserId(token);
        int result = userFavoritesService.deleteFavorite(userId, recipeId);
        if (result == 0) {
            return ResponseUtils.ok("删除收藏成功");
        } else {
            return ResponseUtils.fail(500, "删除收藏失败");
        }
    }

    @GetMapping("/status")
    public Object isUserFavoritesById(@RequestHeader("token") String token,@RequestParam Integer recipeId){
        Integer userId=jwtHelper.verifyTokenAndGetUserId(token);

        if (userId == null && recipeId == null) {
            return ResponseUtils.fail(500,"请登入或者未收藏");
        }
        int result = userFavoritesService.isUserFavoritedRecipe(userId, recipeId);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("liked", result);
        return ResponseUtils.ok(response);
    }
}
